package com.fuyun.microservice.codec;

import com.fuyun.microservice.codec.msg.LoginRequestMessage;
import com.fuyun.microservice.codec.msg.Message;
import com.fuyun.microservice.utils.BufferUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.List;

@Slf4j
@ChannelHandler.Sharable
public class LoginRequestMessageCodec extends MessageToMessageCodec<Message, LoginRequestMessage> {
    @Override
    protected void encode(ChannelHandlerContext ctx, LoginRequestMessage msg, List<Object> out) {
        ByteBuf bodyBuffer =  Unpooled.buffer(40);
        bodyBuffer.writeInt(msg.getClientId());
        bodyBuffer.writeBytes(msg.getClientSecret().getBytes());
        bodyBuffer.writeInt(msg.getClientVersion());

        msg.setBodyBuffer(bodyBuffer.array());
        ReferenceCountUtil.release(bodyBuffer);
        out.add(msg);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, Message msg, List<Object> out) {
        short commandId = msg.getHeader().getCommandId();
        if (commandId != PacketType.CONNECTREQUEST.getCommandId()) {
            //不解析，交给下一个codec
            out.add(msg);
            return;
        }

        LoginRequestMessage loginRequestMessage = new LoginRequestMessage();
        BeanUtils.copyProperties(msg, loginRequestMessage);
        ByteBuf bodyBuffer = Unpooled.wrappedBuffer(msg.getBodyBuffer());
        Long clientId  = bodyBuffer.readUnsignedInt();
        String clientSecret=bodyBuffer.readBytes(32).toString(BufferUtil.CHARSET_DEFAULT);
        Long clientVersion= bodyBuffer.readUnsignedInt();
        loginRequestMessage.setClientId(clientId.intValue());
        loginRequestMessage.setClientSecret(clientSecret);
        loginRequestMessage.setClientVersion(clientVersion.intValue());

        ReferenceCountUtil.release(bodyBuffer);
        out.add(loginRequestMessage);
    }
}
